package com.libleveldb.implementation.mock

import com.libleveldb.LevelDB
import com.libleveldb.Snapshot
import java.lang.ref.WeakReference
import java.util.*

class MockSnapshot(mockLevelDB: MockLevelDB) : Snapshot() {
    private val owner: WeakReference<LevelDB>

    @get:Synchronized
    @Volatile
    override var isReleased: Boolean = false
        get() {
            val owner = owner.get()
            return isReleased || owner == null || owner.isClosed
        }

    @get:Synchronized
    @Volatile
    var snapshot: SortedMap<ByteArray, ByteArray>?
        private set

    fun checkOwnership(owner: LevelDB): Boolean {
        return this.owner.get() === owner
    }

    @Synchronized
    fun release() {
        isReleased = true
        snapshot = null
    }

    init {
        owner = WeakReference(mockLevelDB)
        snapshot = Collections.unmodifiableSortedMap(TreeMap(mockLevelDB.map))
    }
}